package server

import (
	"errors"
	"fmt"
	"log"
)

// Scheduler 调度器
// 负责添加任务，删除任务，执行任务
type Scheduler struct {
	Platforms map[string]*Platform
}

func NewScheduler() *Scheduler {
	return &Scheduler{
		Platforms: make(map[string]*Platform),
	}
}

func (s *Scheduler) AddPlatform(platform *Platform) error {
	if _, ok := s.Platforms[platform.Name]; ok {
		return errors.New(fmt.Sprintf("platform %s exists", platform.Name))
	}
	s.Platforms[platform.Name] = platform
	return nil
}

// StopPlatform  stop platform
func (s *Scheduler) StopPlatform(name string) {
	if p, ok := s.Platforms[name]; ok {
		p.Stop()
	}
}

func (s *Scheduler) RemovePlatform(name string) {
	s.StopPlatform(name)
	// delete platform
	delete(s.Platforms, name)
}

func (s *Scheduler) GetPlatform(name string) (*Platform, error) {
	if p, ok := s.Platforms[name]; ok {
		return p, nil
	}
	return nil, errors.New(fmt.Sprintf("platform %s not exists", name))
}

func (s *Scheduler) Start() {
	go func() {
		err := RunRestfulServer(s)
		if err != nil {
			log.Printf("restful serve start error: %s", err)
		}
	}()
	for _, p := range s.Platforms {
		p.Run()
	}
}
